package com.example.bank.service.user;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.example.bank.dao.ClientDao;
import com.example.bank.dao.UnionDao;
import com.example.bank.dao.UserDao;
import com.example.bank.pojo.User;
import com.example.bank.exception.SystemException;
import com.example.bank.util.JWTUtil;
import com.example.bank.util.ResultUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Leeziqiang
 * @description：UserService实现类
 * @date ：2021/12/3 20:48
 */
@Service
@Transactional
public class UserServiceImpl implements UserService{

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserDao userDao;
    @Autowired
    private UnionDao unionDao;
    @Autowired
    private ClientDao clientDao;


    @Override
    public User getById(String id) {
        if (StrUtil.isEmpty(id) || "undefined".equals(id)) {
            throw new SystemException("param error");
        }
        return userDao.findUserById(id);
    }

    @Override
    public String findUserName(String id) {
        return userDao.findNameById(id);
    }

    @Override
    public Map<String, Object> login(String id, String username) {
        User dbUser = userDao.findUserById(id);
        // 首先判断用户是否已经注册
        if (ObjectUtil.isNull(dbUser)) {
            logger.info("----------用户{}执行了注册操作----------", username);
            // 若尚未注册
            // 用户注册时角色默认为业务员
            User user = new User();
            user.setUserId(id);
            user.setUserName(username);
            int n = userDao.saveUser(user);
            int m = userDao.saveUserRole(id, 1);
            if (n <= 0 || m <= 0) {
                throw new SystemException("注册失败");
            }
        }
        Integer role = userDao.findRoleByUserId(id);
        // 自定义token信息
        String token = JWTUtil.sign(id, JWTUtil.SECRET);
        logger.info("----------用户{}的唯一token为{}----------", username, token);
        return ResultUtil.sign(token, role);
    }

    @Override
    public List<User> listByAgentId(String agentId) {
        if (StrUtil.isEmpty(agentId)) {
            throw new SystemException("param error");
        }
        return userDao.findByAgentId(agentId);
    }

    @Override
    public String findRoleByUserId(String userId) {
        int roleId =  userDao.findRoleByUserId(userId);
        String role = userDao.findRoleById(roleId);
        return role;
    }

    @Override
    public String findPermByRoleId(Integer roleId) {
        int permId =  userDao.findPermByRoleId(roleId);
        String perm = userDao.findPermById(permId);
        return perm;
    }

    @Override
    public String findPermByUserId(String userId) {
        int roleId =  userDao.findRoleByUserId(userId);
        int permId =  userDao.findPermByRoleId(roleId);
        String perm = userDao.findPermById(permId);
        return perm;
    }

    @Override
    public Map<User, List<User>> listAll() {
        Map<User, List<User>> map = new LinkedHashMap<>();
        // 查询所有的经理
        // 查询所有经理的id
        List<String> ids = userDao.findAgents();
        if (ObjectUtil.isEmpty(ids)) {
            return new LinkedHashMap<>();
        }
        List<User> agents = userDao.findUserByIds(ids);
        // 查询对应所有的业务员
        for (User agent : agents) {
            List<User> salesmen = userDao.findByAgentId(agent.getUserId());
            map.put(agent, salesmen);
        }
        return map;
    }

    @Override
    public User adminLogin(String username, String password) {
        logger.info("开始登录");
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            logger.info("管理员账号或密码为空");
            throw new SystemException("管理员账号或密码为空");
        }
        // 首先查询表中是否有改用户
        User user = userDao.findUserById(username);
        // 判断该用户是否为管理员
        if (ObjectUtil.isNull(user)) {
            logger.info("用户不存在");
            throw new SystemException("用户不存在");
        }
        Integer role = userDao.findRoleByUserId(user.getUserId());
        if (role != 3) {
            logger.info("您没有权限");
            throw new SystemException("您没有权限");
        }
        // 判断密码是否正确
        String dbPassword = new Md5Hash(password).toString();
        logger.info(dbPassword);
        if (dbPassword.equals(user.getPassword())) {
            logger.info("成功");
            return user;
        }
        return null;
    }

    @Override
    public List<User> list() {
        List<User> users = userDao.list();
        for (User user : users) {
            Integer roleId = userDao.findRoleByUserId(user.getUserId());
            String bankArea = userDao.findBankAreaById(user.getUserId());
            String role = userDao.findRoleById(roleId);
            if (StrUtil.isEmpty(bankArea)) {
                user.setRole(role);
            } else {
                user.setRole(bankArea+role);
            }
        }
        return users;
    }

    @Override
    public List<User> listAdministrator() {
        List<String> ids = userDao.findAdministrator();
        if (ObjectUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        List<User> administrators = new ArrayList<>();
        for (String id : ids) {
            User administrator = userDao.findUserById(id);
            administrators.add(administrator);
        }
        for (User administrator : administrators) {
            administrator.setRole(administrator.getBankArea()+"经理");
        }
        return administrators;
    }

    @Override
    public List<User> listAgent() {
        List<String> ids = userDao.findAgents();
        if (ObjectUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        List<User> agents = new ArrayList<>();
        for (String id : ids) {
            User agent = userDao.findUserById(id);
            agents.add(agent);
        }
        for (User agent : agents) {
            agent.setRole(agent.getBankArea()+"经理");
        }
        return agents;
    }

    @Override
    public List<User> listSalesman() {
        List<String> ids = userDao.findSalesmen();
        if (ObjectUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        List<User> salesmen = new ArrayList<>();
        for (String id : ids) {
            User salesman = userDao.findUserById(id);
            salesmen.add(salesman);
        }
        for (User salesman : salesmen) {
            salesman.setRole("业务员");
        }
        return salesmen;
    }

    @Override
    public List<User> listSalesman2(String agentId) {
        List<User> salesmen = userDao.findByAgentId(agentId);
        return salesmen;
    }

    // 将业务员设为经理
    @Override
    public boolean assign(String userId, String bankArea) {
        logger.info("bankArea:"+bankArea);
        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(bankArea)) {
            logger.info("userId为空");
            throw new SystemException("param error");
        }
        int roleId = userDao.findRoleByUserId(userId);
        if (roleId == 1) {
            // 将业务员设为经理
            int n = userDao.updateUserRole(userId, 2);
            // 给经理设置银行区域
            int m = userDao.updateBankArea(userId, bankArea);
            if (n > 0 && m > 0) {
                return true;
            }
        } else {
           throw new SystemException("角色错误");
        }
        return false;
    }

    @Override
    public boolean toAdministrator(String userId) {
        if (StrUtil.isEmpty(userId)) {
            throw new SystemException("userId为空");
        }
        int roleId = userDao.findRoleByUserId(userId);
        if (roleId == 1) {
            // 将业务员设为业务员管理员
            int n = userDao.updateUserRole(userId, 4);
            if (n > 0) {
                return true;
            }
        } else {
            throw new SystemException("角色错误");
        }
        return false;
    }

    @Override
    public List<User> unBind(String userId) {
        List<User> users = userDao.unBindUser();
        int roleId = userDao.findRoleByUserId(userId);
        if (roleId == 1) {
            List<User> agents = new ArrayList<>();
            for (User user : users) {
                int id = userDao.findRoleByUserId(user.getUserId());
                if (id == 2) {
                    user.setRole("经理");
                    agents.add(user);
                }
            }
            return agents;
        } else {
            List<User> salesmen = new ArrayList<>();
            for (User user : users ) {
                if (user == null) {
                    break;
                }
                if (1 == userDao.findRoleByUserId(user.getUserId()) && "0".equals(user.getAgentId())) {
                    user.setRole("业务员");
                    salesmen.add(user);
                }
            }
            return salesmen;
        }
    }

    @Override
    public boolean bind(String userId, String agentId) {
        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(agentId)) {
            throw new SystemException("param error");
        }
        int n = userDao.bind(userId, agentId);
        if (n > 0) {
            return true;
        }
        return false;
    }


    // 新增后台删除角色功能
    @Override
    public boolean deleteRole(String userId) {
        if (StrUtil.isEmpty(userId)) {
            throw new SystemException("userId为空");
        }
        // 删除角色
        // tbl_user, tbl_user_role, tbl_union, tbl_user_client
        // 1.首先删除tbl_user中的一条用户记录
        int n1 = userDao.deleteUser(userId);
        // 2.删除tbl_user_role中的一条记录
        int n2 = userDao.deleteUserRole(userId);
        // 3.删除tbl_user_client中的记录
        // 3.1 查询名下的客户
        List<String> clientIds = unionDao.findClientByUserId(userId);
        // 3.2 查询完之后将union关系删除
        int n3 = unionDao.delete(userId);
        // 4.删除tbl_client中用户名下的所有客户
        for (String id : clientIds) {
            clientDao.removeClient(id);
        }
        return true;
    }
    // 新增后台撤销角色权限功能
    @Override
    public boolean withdrawPerm(String userId) {
        // 把角色重新变为业务员
        userDao.updateUserRole(userId, 1);
        userDao.updateUserByAgentId(userId);
        userDao.updateArea(userId);
        return true;
    }

    // 新增后台设置真实姓名功能
    @Override
    public boolean setRealName(String userId, String realName) {
        if (StrUtil.isEmpty(userId)) {
            throw new SystemException("userId为空");
        }
        int n = userDao.updateRealName(userId, realName);
        if (n > 0) {
            return true;
        }
        return false;
    }


}
